package com.gitee.qdbp.base.shiro.validate;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.shiro.web.util.WebUtils;
import com.gitee.qdbp.able.exception.ServiceException;
import com.gitee.qdbp.able.result.ResultCode;
import com.gitee.qdbp.base.error.BaseCtlErrorCode;
import com.gitee.qdbp.base.shiro.filter.JsonSupportLoginSubmissionFilter;
import com.gitee.qdbp.tools.utils.VerifyTools;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.servlet.KaptchaServlet;

/**
 * 图片验证码校验类
 *
 * <pre>
 * &lt;bean id="kaptchaValidator" class="{pkg}.KaptchaValidator"&gt;
 *     &lt;property name="captchaParam" value="captcha" /&gt;
 * &lt;/bean&gt;
 * </pre>
 *
 * @author zhaohuihua
 * @see JsonSupportLoginSubmissionFilter
 * @see KaptchaServlet KaptchaServlet in web.xml
 * @version 150920
 */
public class KaptchaValidator implements IParamValidator {

    private static final String CAPTCHA_DISABLED = "DISABLED";

    /** 图片验证码的参数名 **/
    private String captchaParam = "captcha";

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean doValidate(ServletRequest request, ServletResponse response) throws ServiceException {
        if (CAPTCHA_DISABLED.equals(this.captchaParam)) {
            return true; // 不启用验证码校验
        }

        // 参数提交的验证码
        String captchaInParam = getCaptchaValue(request);
        if (VerifyTools.isBlank(captchaInParam)) {
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }

        HttpSession session = WebUtils.toHttp(request).getSession();
        // session中的验证码
        String captchaInSession = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (captchaInSession == null) {
            throw new ServiceException(BaseCtlErrorCode.USER_LOGIN_CAPTCHA_ERROR);
        }

        // 判断是否相等
        if (!captchaInSession.equalsIgnoreCase(captchaInParam)) {
            throw new ServiceException(BaseCtlErrorCode.USER_LOGIN_CAPTCHA_ERROR);
        }
        return true;
    }

    protected String getCaptchaValue(ServletRequest request) {
        return WebUtils.getCleanParam(request, captchaParam);
    }

    /**
     * 设置captchaParam
     *
     * @param captchaParam captchaParam
     */
    public void setCaptchaParam(String captchaParam) {
        this.captchaParam = captchaParam;
    }
}
